/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-03-04     17481       the first version
 */
#include <COMMON_HEADER/common_header.h>

#define DTU_ULOG_FILE   "file"
#define DTU_ULOG_FILE_PATH  "/logs"
#define DTU_DATA_FILE_PATH  "/data"

#define DTU_ULOG_FILE_NAME  "ulog.log"
#define DTU_DATA_FILE_NAME  "udata.data"


#define FILE_MAX_NUM   16
#define ULOG_FILE_MAX_SIZE   (1024 * 512)

#define ULOG_FILE_MAX_NUM 6

#define DTU_ULOG_FILE_PATH_LEN  255

/*定义SPI flash 后端*/
static struct ulog_backend ulog_spi_flash_file;

//清楚多余的日志文件
void clear_redundant_ulog_file()
{
    uint8_t count = 0;
    char ulog_file_pathname[256] = {0};
    char ulog_file_pathname_[256] = {0};
    char read_dir_pathname[256] = {0};
    DIR *dirp;
    struct dirent *d;

    uint8_t flag = 0;

    char str_stoke[1] = {'_'};

    char *year = NULL;
    char *year_= NULL;
    char *month = NULL;
    char *month_ = NULL;
    char *day = NULL;
    char *day_ = NULL;

    /* 打开 /logs 目录 */
    dirp = opendir("/logs");
    if (dirp == RT_NULL)
    {
        ;
    }
    else
    {
        /* 读取目录 */
        while ((d = readdir(dirp)) != RT_NULL)
        {
            //如果是获取到第一个日志文件名，那么放置到数组中
            if(count == 0)
            {
                for(int i = 0;i<sizeof(d->d_name);i++)
                {
                    ulog_file_pathname[i] = (d->d_name)[i];
                }
            }
            //比较现在读到的和上一个日志谁更早，保存最早
            else
            {
                for(int i = 0;i<sizeof(d->d_name);i++)
                {
                    read_dir_pathname[i] = (d->d_name)[i];
                }
                for(int i = 0;i<sizeof(ulog_file_pathname);i++)
                {
                    ulog_file_pathname_[i] = ulog_file_pathname[i];
                }
                year = strtok(ulog_file_pathname, str_stoke);
                month = strtok(NULL, str_stoke);
                day = strtok(NULL, str_stoke);

                year_ = strtok(d->d_name, str_stoke);
                month_ = strtok(NULL, str_stoke);
                day_ = strtok(NULL, str_stoke);

                if(atoi(month) > atoi(month_))
                {
                    flag = 1;
                }
                else if(atoi(month) == atoi(month_))
                {
                    if(atoi(day) > atoi(day_))
                    {
                        flag = 1;
                    }
                    else
                    {
                        flag = 0;

                    }
                }
                else
                {
                    flag = 0;
                }
                if(flag == 1)
                {
                    memset(ulog_file_pathname_,0,256);
                    for(int i = 0;i<sizeof(read_dir_pathname);i++)
                    {
                        ulog_file_pathname_[i] = read_dir_pathname[i];
                    }
                }
            }
            count += 1;
            if(count >= ULOG_FILE_MAX_NUM)
            {
                memset(ulog_file_pathname,0,256);
                sprintf(ulog_file_pathname, "/logs/");
                //拼接绝对路径目录
                strcat(ulog_file_pathname, ulog_file_pathname_);
                //删除最早的日志
                if(unlink(ulog_file_pathname) < 0)
                {
                    rt_kprintf("删除最早日志:%s 失败\n", ulog_file_pathname);
                }
                else
                {
//                    rt_kprintf("删除最早日志:%s 成功\n", ulog_file_pathname);
                    ;
                }
            }
        }

    }
    /* 关闭目录 */
    closedir(dirp);
}

int create_file(const char *file_path,const char*file_name,int file_year,int file_month,int file_day)
{
    char dtu_file_path[DTU_ULOG_FILE_PATH_LEN] = {0};
    int log_file_fd = -1;
    rt_sprintf( dtu_file_path, "%s/%d_%d_%d_%s", file_path,file_year,file_month, file_day,file_name);
    log_file_fd = open(dtu_file_path, O_CREAT | O_RDWR | O_APPEND);
    if(log_file_fd == -1)
    {
        rt_kprintf("open new file fail:%s\n",dtu_file_path);
    }
    else
    {
        ;
    }
    return log_file_fd;
}


/**
 *将日志写入到对应的文件中，并同步到存储设备上，写入完成后，并关闭该文件
 * @param log    写入的日志数据
 * @param len    写入的日志数据长度
 * @return
 */
void  write_fsync_flie(const char *log , size_t len, int log_file_fd)
{
    write(log_file_fd,log,len);
    fsync(log_file_fd);
}

/*控制后端文件输出日志函数*/
static void ulog_file_backend_output(struct ulog_backend *backend, rt_uint32_t level, const char *tag, rt_bool_t is_raw, const char *log, size_t len)
{
    int log_file_fd = -1;
    char dtu_file_path[DTU_ULOG_FILE_PATH_LEN] = {0};
    //检查日志路径是否存在
    if(access(DTU_ULOG_FILE_PATH, 0))
    {
        //不存在就建立日志路径
        mkdir(DTU_ULOG_FILE_PATH,0x777);
    }
    dtu_time_update();
    rt_sprintf( dtu_file_path, "%s/%d_%d_%d_%s", DTU_ULOG_FILE_PATH,dtu_times.year,dtu_times.month, dtu_times.day,DTU_ULOG_FILE_NAME);
    log_file_fd = open(dtu_file_path, O_CREAT | O_RDWR | O_APPEND);
    if(log_file_fd == -1)
    {
       rt_kprintf("open new file fail:%s\n",dtu_file_path);
    }
    else
    {
        write(log_file_fd,log,len);
        fsync(log_file_fd);
    }
    close(log_file_fd);
}

//初始化日志异步输出后端控制台
int ulog_file_backend_init()
{
    //设定输出函数
    ulog_spi_flash_file.output = ulog_file_backend_output;
    /*注册到后端*/
    ulog_backend_register(&ulog_spi_flash_file, DTU_ULOG_FILE, RT_TRUE);
    return 0;
}

//INIT_COMPONENT_EXPORT(ulog_file_backend_init);
